package com.igeek.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.igeek.domain.*;
import com.igeek.service.OrderService;
import com.alipay.config.AlipayConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author jerryHe
 * @create 2019-10-08 15:59
 */

@WebServlet("/orderServlet")
public class OrderServlet extends BaseServlet {

    public void submitOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        1. 先登录
//        2. 把购物车中的信息存入数据库
//        3. 展现订单信息
        //假设登录后session中存在一个user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null){
            //跳转到登录页面
            response.sendRedirect("login.jsp");
            //终止执行后面代码
            return;
        }
        //订单表需要的数据 oid 订单编号 ,total 总价,uid在user对象中
        String oid = UUID.randomUUID().toString();
        //总价在session的购物车中
        Cart cart = (Cart) session.getAttribute("cart");
        double total = cart.getTotal();
        //把3个参数放入订单对象中
        Order order = new Order(oid,total,user);

        //把购物车中CartItem转入OrderItem
        //map--list
        List<OrderItem> orderItems = new ArrayList<>();
        Map<String,CartItem> map = cart.getCartItems();
        //遍历map
        for(Map.Entry<String,CartItem> entry : map.entrySet()){
            //itemid 主键 count subtotal Product Order
            String itemid = UUID.randomUUID().toString();
            CartItem cartItem = entry.getValue();
            int count = cartItem.getBuyNum();
            double subtotal = cartItem.getSubTotal();
            Product product = cartItem.getProduct();
            //构建OrderItem对象
            OrderItem orderItem = new OrderItem(itemid,count,subtotal,product,order);
            //把orderitem放入list
            orderItems.add(orderItem);
        }
        //把orderitem放入order对象
        order.setOrderItems(orderItems);
        //调用service，保存订单数据
        OrderService orderService = new OrderService();
        orderService.save(order);
        //把订单数据放入session
        session.setAttribute("order",order);
        //跳转页面
        response.sendRedirect("order_info.jsp");

    }

    public void confirmOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //支付
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String oid = request.getParameter("oid");
        //付款金额，必填
        String total_amount = request.getParameter("total_amount");
        //订单名称，必填
        String subject = "testOrder";
        //商品描述，可空
        String body = "testBody";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ oid +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.getWriter().write(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

/*
        //1.接收参数
        String address = request.getParameter("address");
        String name = request.getParameter("name");
        String telephone = request.getParameter("telephone");

        Order order = new Order(oid,address,name,telephone);
        //2.调用service
        OrderService service = new OrderService();
        service.update(order);
        //3.返回结果*/
    }
}
